define([
    'base',
    'bootstrapDialog',
    'bootstrapTable'
], function (base, BootstrapDialog) {
    //默认加载基础库
    base();

    /**
     * form表单转换成json
     */
    function getFormJson(form) {
        var data = {};
        var a = $(form).serializeArray();
        $.each(a, function () {
            if (data[this.name] !== undefined) {
                if (!data[this.name].push) {
                    data[this.name] = [data[this.name]];
                }
                data[this.name].push(this.value || '');
            } else {
                data[this.name] = this.value || '';
            }
        });
        return data;
    }

    return {
        list: function () {
            var myTable = $('#flowList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: 'api.json'})
            };
            //table按需刷新动作
            var doAction = function (obj) {
                myTable.bootstrapTable('refresh', {url: 'api.json?pid=' + obj.id})
            };

            //table当前行的响应事件
            window.operateEvents = {
                'click .update': function (e, value, row) {
                    winModal("编辑", row);
                },

                'click .template': function (e, value, row) {
                    //流程模板
                    window.location.href = '../template/save/' + row.id;
                },

                'click .status': function (e, value, row) {
                    $.baseUtils.oneStatus({
                        row: row,
                        tableName: myTable,
                        nameText: '流程',
                        nameValue: row.flowName,
                        url: '../status/action'
                    });
                },
                'click .delete': function (e, value, row) {
                    $.baseUtils.oneDelete({
                        row: row,
                        tableName: myTable,
                        nameText: '流程',
                        nameValue: row.flowName,
                        url: '../delete/action'
                    });
                }
            };

            //table表格
            myTable.bootstrapTable({
                url: 'api.json', // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [{ // 列设置
                    field: 'state',
                    checkbox: true // 使用复选框
                },
                    {
                        field: 'id',
                        title: '编号'
                    }, {
                        field: 'flowName',
                        title: '名称'
                    }, {
                        field: 'itemCode',
                        title: '事项编码'
                    },
                    {
                        field: 'updateName',
                        title: '更新人'
                    }, {
                        field: 'updateTime',
                        title: '更新时间',
                        align: 'center'
                    }, {
                        field: 'status',
                        title: '状态',
                        align: 'center',
                        formatter: function (value, row, index) {
                            if (value == 1) {
                                return '<span class="label label-primary">正常</span>';
                            } else {
                                return '<span class="label label-danger">已禁</span>';
                            }
                        }
                    }, {
                        field: 'action',
                        title: '操作',
                        align: 'center',
                        formatter: operateFormatter,
                        events: operateEvents
                    }
                ]
            });

            //搜索刷新
            $('#search').on('click', function () {
                tableRefresh();
            });

            //toolbar按钮相应事件
            //新增
            $(".toolbar-save").on('click', function () {
                winModal("新增", null);
            });
            //刷新
            $(".toolbar-refresh").on('click', function () {
                tableRefresh();
            });

            //批量修改状态
            $(".toolbar-batchStatus").on('click', function () {
                var entityList = myTable.bootstrapTable('getSelections');
                var row = [], names = [];
                $.each(entityList, function (i, v) {
                    names.push(v.flowName);
                    row.push(v.id);
                });
                if (row.length > 0) {
                    $.baseUtils.batchAction({
                        row: row,
                        tableName: myTable,
                        nameText: '流程',
                        nameValue: names,
                        url: '../status/batchAction'
                    });
                } else {
                    msgTool.error("请选择虽少一条记录后再操作", "信息提示");
                }

            });


            //搜索参数传递
            function queryParams(params) {
                params.search = $(".searchValue").val().trim();
                return {
                    limit: params.limit,
                    offset: params.offset,
                    search: params.search
                };
            }

            //回显
            function responseHandler(res) {
                return res.rows;
            }


            //模态框
            function winModal(title, row) {
                BootstrapDialog.show({
                    type: BootstrapDialog.TYPE_DEFAULT,
                    tabindex: null,//解决select2搜索框失去焦点的问题
                    title: title,
                    closable: true,	//关闭箭头启动
                    closeByBackdrop: false,	//点击空白不消失
                    closeByKeyboard: true,//ESC取消禁用
                    message: $('<div></div>').load('../save/form.html'),
                    data: {
                        'row': row
                    },
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white cancel',
                        icon: 'fa fa-times',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: '提交' + title,
                        //hotkey: 13,//回车提交
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialog) {
                            //返回验证结果
                            var flag = false;
                            flag = $("#winModal").validate().form();
                            if (flag) {
                                $.baseUtils.ajax({
                                    dialog: dialog,
                                    url: '../save/action',
                                    data: $("#winModal").serialize(),
                                    text: "保存",
                                    isTable: true,
                                    tableName: '#flowList',
                                    isDialog: true
                                })
                            }
                        }
                    }],
                    onshown: function (dialog) {
                        if (row != null) {
                            $('#id').val(row.id);
                            $('#flowName').val(row.flowName);
                            $('#itemCode').val(row.itemCode);
                        }
                    }
                });
            }
        },
        template: function (flowId) {
            //添加流程步骤
            $("#addStep").on('click', function () {
                $("#step-box h3").hide();
                var length = $("form").length + 1;
                // $("#step-box").append("<form class=\"form-horizontal\" name=\"flowTemplateForm\" id=\"flowTemplate_" + length + "\" method=\"post\" role=\"form\"><input value=\""+flowId+"\" name=\"flowId\" type=\"hidden\"><div class=\"panel panel-default\"><div class=\"panel-heading\"><b class=\"text step-title\">流程步骤" + length + "：</b><div class=\"pull-right\"><button onclick=\"$(this).parents('.panel').remove()\" class=\"btn btn-danger\">&nbsp;删除&nbsp;</button></div></div><div class=\"panel-body\"><div class=\"form-group\"><div class=\"col-sm-3\"><label class=\"control-label\">步骤名称：</label><input name=\"stepName\" class=\"form-control\" type=\"text\" required aria-required=\"true\" maxlength='30' placeholder=\"请输入步骤名称\"></div><div class=\"col-sm-3\"><label class=\"control-label\">步骤编号：</label><input name=\"stepCode\" class=\"form-control\" type=\"number\" placeholder=\"请输入步骤编号\" required='required'></div><div class=\"col-sm-3\"><label class=\"control-label\">指定处理角色ID：</label><input name=\"roleId\" class=\"form-control\" type=\"number\" required aria-required=\"true\" placeholder=\"请输入指定处理角色ID\"></div><div class=\"col-sm-3\"><label class=\"control-label\">步骤排序：</label><input name=\"stepOrder\" class=\"form-control\" type=\"number\" placeholder=\"请输入步骤排序\" required='required'></div></div><div class=\"form-group\"><div class=\"col-sm-3\"><label class=\"control-label\">认领：</label><input name=\"claim\" class=\"form-control\" type=\"text\" required aria-required=\"true\" maxlength='30' placeholder=\"请输入认领的状态码\"></div><div class=\"col-sm-3\"><label class=\"control-label\">办理：</label><input name=\"handle\" class=\"form-control\" type=\"number\" placeholder=\"请输入办理的状态码\" required='required'></div><div class=\"col-sm-3\"><label class=\"control-label\">拒绝：</label><input name=\"refuse\" class=\"form-control\" type=\"number\" required aria-required=\"true\" placeholder=\"请输入拒绝的状态码\"></div><div class=\"col-sm-3\"><label class=\"control-label\">同意：</label><input name=\"pass\" class=\"form-control\" type=\"number\" placeholder=\"请输入同意的状态码\" required='required'></div></div></div></div></form>");
                $("#step-box").append("<form class=\"form-horizontal\" name=\"flowTemplateForm\" id=\"flowTemplate_" + length + "\" method=\"post\" role=\"form\"><input value=\"" + flowId + "\" name=\"flowId\" type=\"hidden\"><div class=\"panel panel-default\"><div class=\"panel-heading\"><b class=\"text step-title\">流程步骤" + length + "：</b><div class=\"pull-right\"><button onclick=\"$(this).parents('.panel').remove()\" class=\"btn btn-danger\">&nbsp;删除&nbsp;</button></div></div><div class=\"panel-body\"><div class=\"form-group\"><div class=\"col-sm-3\"><label class=\"control-label\">步骤名称：</label><input name=\"stepName\" class=\"form-control\" type=\"text\" maxlength=\"30\" placeholder=\"请输入步骤名称\" aria-required=\"true\" required></div><div class=\"col-sm-3\"><label class=\"control-label\">步骤编码：</label><input name=\"stepCode\" class=\"form-control\" type=\"text\" placeholder=\"请输入步骤编码\" aria-required=\"true\" required></div><div class=\"col-sm-3\"><label class=\"control-label\">办理角色编号：</label><input name=\"roleId\" class=\"form-control\" type=\"number\" placeholder=\"请输入办理角色编号\" aria-required=\"true\" required></div><div class=\"col-sm-3\"><label class=\"control-label\">步骤排序：</label><input name=\"stepOrder\" class=\"form-control\" type=\"number\" placeholder=\"请输入步骤顺序\" aria-required=\"true\" required></div></div><div class=\"form-group\"><div class=\"col-sm-3\"><label class=\"control-label\">待办理-状态码：</label><input name=\"claim\" class=\"form-control\" type=\"number\" placeholder=\"请输入认领的状态码\" aria-required=\"true\" required></div><div class=\"col-sm-3\"><label class=\"control-label\">办理中-状态码：</label><input name=\"handle\" class=\"form-control\" type=\"number\" placeholder=\"请输入办理的状态码\" aria-required=\"true\" required></div><div class=\"col-sm-3\"><label class=\"control-label\">拒绝办理-状态码：</label><input name=\"refuse\" class=\"form-control\" type=\"number\" placeholder=\"请输入拒绝的状态码\" aria-required=\"true\" required></div><div class=\"col-sm-3\"><label class=\"control-label\">同意办理-状态码：</label><input name=\"pass\" class=\"form-control\" type=\"number\" placeholder=\"请输入同意的状态码\" aria-required=\"true\" required></div></div></div></div></form>");
            });
            //提交流程
            $("#doSubmit").on('click', function () {
                    var dataFormStatus = false;
                    var form = $("form[name='flowTemplateForm']");
                    $.each(form, function () {
                        dataFormStatus = $(this).validate().form();
                    });
                    dataFormStatus = true;
                    if (dataFormStatus) {
                        var length = form.length;
                        //定义要传递的数组
                        var flowTemplateList = [];
                        for (var i = 1; i <= length; i++) {
                            var formJson = getFormJson($("#flowTemplate_" + i));
                            flowTemplateList.push(formJson);
                        }
                        $.ajax({
                            url: "/flow/template/save/action",
                            type: 'POST',
                            data: JSON.stringify(flowTemplateList),
                            dataType: "JSON",
                            contentType: 'application/json;charset=utf-8',
                            // beforeSend: function () {
                            //     //触发ajax请求开始时执行
                            //     $("#doSubmit").text('提交中...');
                            //     $("#doSubmit").attr('disabled', 'disabled');
                            // },
                            success: function (data) {
                                if (data.success) {
                                    window.location.href = "/flow/view/index";
                                } else {
                                    msgTool.error(data.msg);
                                }
                            },
                            error: function (error) {
                                msgTool.error("操作失败，请刷新当前页面后重试！");
                            },
                            complete: function () {
                                $("#doSubmit").text("保存");
                                $("#doSubmit").removeAttr('disabled');
                            }
                        });
                    }
                }
            );
        }
    }
});






